package com.mar.bt.rd.launch;

import java.awt.AWTException;
import java.io.IOException;
import java.util.Scanner;

import javax.bluetooth.RemoteDevice;

import com.mar.bt.rd.server.ServerSideHandler;
import com.mar.bt.server.BTServerFactory;
import com.mar.bt.server.IBTClientsListener;
import com.mar.bt.server.IBluetoothIOHandler;
import com.mar.bt.server.IBluetoothServer;
/**
 * USE: Launch main. To exit correctly just type 'exit' in server console.<bt/>
 * NOTE: Multiple application instances might produce conflicts and would not work at all.
 * @author mar
 */
public class Launcher {
	static boolean isAnyClientConnected  = false;
	static IBluetoothServer serv;
	 
	/**	
	 * 
	 * @param args
	 *            the command line arguments
	 * @throws java.io.IOException
	 * @throws java.awt.AWTException
	 */
	public static void main(String[] args) {
		System.out.println("Starting mega server...");
		serv = BTServerFactory.getInstance().createServer();
		serv.startListening( new IBTClientsListener() {
			public void clientConnected(RemoteDevice clientDev,
					IBluetoothIOHandler btIOHadler) {
				try {
					System.out.println("Connected");
					new ServerSideHandler(btIOHadler);

					if (!isAnyClientConnected){
						isAnyClientConnected = true;
						System.out.println("Type 'exit' to shutdown.");
						Scanner scanner = new Scanner(System.in);
						
						while ( !scanner.next().equals("exit") ){
							//
						}
						serv.shutdown();
						System.exit(0);
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (AWTException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

}
